package com.salon.modules.app.interceptor;

import com.salon.common.exception.CustomException;
import com.salon.modules.app.annotation.Login;
import com.salon.modules.app.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * APP权限(Token)验证拦截器验证APP端接口登录
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    public static final String USER_KEY = "userId";

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest req, @NotNull HttpServletResponse res, @NotNull Object handler) {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }
        if (annotation == null) {
            return true;
        }
        // 获取凭证
        String token = req.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = req.getParameter(jwtUtils.getHeader());
        }
        // 凭证为空
        if (StringUtils.isBlank(token)) {
            throw new CustomException(HttpStatus.UNAUTHORIZED.value(), jwtUtils.getHeader() + "不能为空");
        }
        // token验证
        Claims claims = jwtUtils.getClaimByToken(token);
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
            throw new CustomException(HttpStatus.UNAUTHORIZED.value(), jwtUtils.getHeader() + "失效，请重新登录");
        }
        // 设置userId到request里，后续根据userId，获取用户信息
        req.setAttribute(USER_KEY, Long.parseLong(claims.getSubject()));
        return true;
    }

}
